package com.imooc.controller;

import com.imooc.config.ProjectUrlConfig;
import com.imooc.constant.CookieConstant;
import com.imooc.constant.RedisConstant;
import com.imooc.dataobject.SellerInfo;
import com.imooc.enums.ResultEnum;
import com.imooc.service.SellerService;
import com.imooc.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述: <br>
 * (卖家用户处理)
 *
 * @Author:Mr. xyb
 * @Date: 2018/5/18 17:34
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Controller
@Slf4j
@RequestMapping("/seller")
public class SellerUserController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    /**
     * 登录，此处使用微信扫码登录，需要使用微信开放平台
     *
     * @param openid
     * @param request
     * @param response
     * @param map      返回参数
     * @return
     */
    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid, HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) {

        /*1、判断openid对应的用户是否存在数据库中，*/
        SellerInfo info = sellerService.findSellerInfoByOpenid(openid);
        if (info == null) {
            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            map.put("url", "/sell/seller/order/list");
            return new ModelAndView("common/error", map);
        }

        /**
         * 2、把token写入redis
         *    使用uuid生成token
         *    生成过期时间
         */
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;// 过期时间
        /**
         * 参数解读：1、格式化key（TOKEN_为前缀），2、openid为value，3、过期时间，4、时间单位（秒）
         * 此处以token_uuid为key，openid为值，保存到redis中
         * 然后将token_uuid保存到cookie中，之后从cookie中通过token属性读取token_uuid，再使用token_uuid从redis中读取openid
         */
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX + "%s", token), openid, expire, TimeUnit.SECONDS);
        /*3、把token保存值cookie*/
        CookieUtils.setCookie(request, response, CookieConstant.TOKEN,
                token, expire);
        return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list");
    }


    /**
     * 登出
     *
     * @param request
     * @param response
     * @param map      返回参数
     * @return
     */
    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) {

        //1、查询cookie
        String tokenValue = CookieUtils.getCookieValue(request, CookieConstant.TOKEN);

        if (tokenValue != null) {// 如果token不为空
            /*干掉redis中的token值*/
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX + "%s", tokenValue));
            /*干掉cookie中的token*/
            CookieUtils.deleteCookie(request, response, CookieConstant.TOKEN);
        }
        map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());
        map.put("url", "/sell/seller/order/list");
        return new ModelAndView("common/success", map);
    }

}
